package com.hetang.maijiayun.report.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hetang.maijiayun.api.eshop.EShop;
import com.hetang.maijiayun.api.eshop.IEShopService;
import com.hetang.maijiayun.api.report.IOrderSaleReportService;
import com.hetang.maijiayun.api.report.model.OrderSaleReport;
import com.hetang.maijiayun.api.report.model.OrderSaleReportDetail;
import com.hetang.maijiayun.api.report.model.SkuSaleReportDetail;
import com.hetang.maijiayun.api.util.APIException;
import com.hetang.maijiayun.api.util.AndQuery;
import com.hetang.maijiayun.api.util.OrQuery;
import com.hetang.maijiayun.api.util.Page;
import com.hetang.maijiayun.api.util.PageResultSet;
import com.hetang.maijiayun.report.mappers.OrderSaleReportMapper;
import com.hetang.maijiayun.report.mappers.SkuSaleReportMapper;
import com.hetang.maijiayun.report.utils.CustomerContextHolder;
import com.hetang.maijiayun.utils.security.SecuritySession;

/**
 * 订单销售报表
 * 
 * @author yangfan
 */
@Service("orderSaleReportService")
public class OrderSaleReportServiceImpl implements IOrderSaleReportService {
	@Autowired
	OrderSaleReportMapper orderSaleReportMapper;
	@Autowired
	SkuSaleReportMapper skuSaleReportMapper;
	@Autowired
	IEShopService iEShopService;
	

	public static final Logger logger = LoggerFactory.getLogger(OrderSaleReportServiceImpl.class);

	public PageResultSet<OrderSaleReportDetail> getOrderSaleReportDetail(JSONObject param, SecuritySession session) throws APIException {
		if (Objects.isNull(param)) {
			APIException.builder().illegalArgError().errorMsg("查询参数不能为空").throwExcetion();
		}
		List<OrderSaleReportDetail> reportDatas = new ArrayList<OrderSaleReportDetail>();
		
		// 根据分页参数生成limit所需数据
		Integer pageNo = Objects.isNull(param.getInteger("pageNo")) ? 1 : param.getInteger("pageNo");
		Integer pageSize = param.getInteger("pageSize") == null ? 50 : param.getInteger("pageSize");
		Page page = new Page(pageNo,pageSize);
		
		CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_SLAVE);
		EShop[] eshops = iEShopService.getList(session.tenantry.id, session.user.id, new AndQuery(), new OrQuery(), "id", true, session);
		if(Objects.isNull(eshops) || eshops.length == 0){
			return new PageResultSet<OrderSaleReportDetail>(page, 0, reportDatas);
		}
		fullConditionWithPower(param, eshops, session);//补充相应的参数,租户,以及店铺权限
		
		// 查询总条数
		Integer totalNum = orderSaleReportMapper.countOrderSaleReportDetail(param);
		if(totalNum > 0){
			param.put("pageLimitClause", (pageNo - 1) * pageSize + "," + pageSize);
			// 查出选择日期内,每天的统计数据
			reportDatas = orderSaleReportMapper.getOrderSaleReportDetail(param);
			if(CollectionUtils.isNotEmpty(reportDatas)){//补充店铺名称
				Map<String,String> shopCodeShopNameMap = new HashMap<String,String>();
				for (EShop eShop : eshops) {
					shopCodeShopNameMap.put(eShop.getB2cCode(), eShop.getTitle());
				}
				for (OrderSaleReportDetail detail : reportDatas) {
					detail.setEshopName(shopCodeShopNameMap.get(detail.getEshopCode()));
				}
			}
		}
		return new PageResultSet<OrderSaleReportDetail>(page, totalNum, reportDatas);
	}

	/**
	 * 商品销售统计汇总
	 */
	@Override
	public OrderSaleReport getOrderSaleReport(JSONObject param, SecuritySession session) throws APIException {
		if (Objects.isNull(param)) {
			param = new JSONObject();
		}
		CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_SLAVE);
		EShop[] eshops = iEShopService.getList(session.tenantry.id, session.user.id, new AndQuery(), new OrQuery(), "id", true, session);
		if(Objects.isNull(eshops) || eshops.length == 0){
			return new OrderSaleReport();
		}
		fullConditionWithPower(param, eshops, session);//补充相应的参数,租户,以及店铺权限
		return orderSaleReportMapper.getOrderSaleReport(param);
	}
	
	@Override
	public List<SkuSaleReportDetail> getSkuSaleReportDetailByOrderId(JSONObject param, SecuritySession session) throws APIException {
		if(Objects.isNull(param) || Objects.isNull(param.getLong("orderId"))){
			APIException.builder().illegalArgError().errorMsg("查询参数不能为空").throwExcetion();
		}
		CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_SLAVE);
		param.put("tenantryId", session.tenantry.id);
		return skuSaleReportMapper.getSkuSaleReportDetail(param);
	}
	
	public void fullConditionWithPower(JSONObject param, EShop[] eshops, SecuritySession session){
		param.put("tenantryId", session.tenantry.id);
		JSONArray eshopCodeArr = param.getJSONArray("eshopCodes");
		// 增加店铺权限 FIXME 前端已经过滤过,如果指定了店铺,这里无需比较了 当然如果数据权限要求特别严格,这里还是在比较下
		if(CollectionUtils.isEmpty(eshopCodeArr) && !session.user.isAdmin){
			List<String> eshopCodes = new ArrayList<String>();
			for (EShop eShop : eshops) {
				eshopCodes.add(eShop.getB2cCode());
			}
			param.put("eshopCodes", eshopCodes);
		}
	}

}
